/**
 * 
 */
package com.feonix.common.util.security;

import java.util.HashSet;
import java.util.Set;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.parser.Parser;

import com.feonix.common.util.FileUtil;
import com.feonix.common.util.StringUtil;

/**
 * @CopyRight (c)1993-2017
 * @Project m-complat-common
 * @Comments 文件过滤类
 * @NameSpace com.feonix.common.util.security
 * @Author Feonixzw
 * @CreateDate 2017年11月28日
 */
public class FileTypeChecker {

	private static Set<String> whiteListCollection = new HashSet<String>();

	private static Set<String> blackListCollection = new HashSet<String>();

	static {

	}

	/**
	 * 初始化黑白名单的数据集合
	 */
	public static void init() {

		String filePath = FileTypeChecker.class.getClassLoader().getResource("").getPath()
				+ "pub/config/security/filefilter.xml";
		String fileStr = FileUtil.readFileToString(filePath);
		Document document = Jsoup.parse(fileStr, "", Parser.xmlParser());
		String whiteList = document.select("upload>white_list").text();
		String blackList = document.select("upload>black_list").text();
		fillList(whiteListCollection, whiteList);
		fillList(blackListCollection, blackList);

	}
	
	/**
	 * 塞值
	 * @param list
	 * @param words
	 */
	private static void fillList(Set<String> list, String words){
		if (StringUtil.isNotEmpty(words)) {
			String[] wordArray = StringUtil.split(words, ",");
			for (String word : wordArray) {
				word = StringUtil.getString(word).trim().toLowerCase();
				if (StringUtil.isNotEmpty(word))
					list.add(word);
			}
		}
	}
	
	public static boolean valid(String fileName) {
		boolean isVaild = false;
		String fileExtension = StringUtil.getString(FileUtil.getExtension(fileName)).trim().toLowerCase();
		if (!(blackListCollection.contains(fileExtension)) && (whiteListCollection.contains(fileExtension))){
			isVaild = true;
		}
		return isVaild;
	}

}
